package guoanmaker.operator.business.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import guoanmaker.operator.business.dao.OperatorProviderOrderDao;
import guoanmaker.operator.business.dao.OperatorUserInfoDao;
import guoanmaker.operator.business.model.OperatorCode;
import guoanmaker.operator.business.model.OperatorDepartment;
import guoanmaker.operator.business.model.OperatorMailConfig;
import guoanmaker.operator.business.model.OperatorQueryMailRecord;
import guoanmaker.operator.business.model.OperatorRole;
import guoanmaker.operator.business.model.OperatorRoleUser;
import guoanmaker.operator.business.model.OperatorSyspage;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.model.Personelinfo;
import guoanmaker.operator.business.model.ProvideCommodity;
import guoanmaker.operator.business.model.ProvideOrderForm;
import guoanmaker.operator.business.model.ProviderBusiness;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.BusinessServer;
import guoanmaker.operator.business.modelnobind.OperatorBusinessAndUser;
import guoanmaker.operator.business.modelnobind.OperatorUserRo;
import guoanmaker.operator.business.modelnobind.Orderforbusiness;
import guoanmaker.operator.business.repository.OperatorCodeRepository;
import guoanmaker.operator.business.repository.OperatorDepartmentRepository;
import guoanmaker.operator.business.repository.OperatorMailConfigRepository;
import guoanmaker.operator.business.repository.OperatorQueryMailRecordRepository;
import guoanmaker.operator.business.repository.OperatorRoleRepository;
import guoanmaker.operator.business.repository.OperatorRoleUserRepository;
import guoanmaker.operator.business.repository.OperatorScreenUsersRepository;
import guoanmaker.operator.business.repository.OperatorSyspageRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;
import guoanmaker.operator.business.repository.ProviderBusinessRepository;
import guoanmaker.operator.helper.common.util.HttpGetUtil;
import guoanmaker.operator.helper.common.util.StdRandom;
import guoanmaker.operator.helper.common.util.StringUtil;

/**
 * Mock implementation.
 * 
 * @author vladimir.stankovic
 *
 *         Aug 4, 2016
 */
@Service
public class OperatorUserService implements OperatorUserServiceInterface {
	private final OperatorUserRepository operatorUserRepository;
	private final OperatorSendCodeService operatorSendCodeService;

	@Autowired
	private OperatorUserInfoDao operatorUserInfoDao;

	@Autowired
	private PersonalUserRepository personalUserRepository;

	@Autowired
	private ProvideOrderFormRepository provideOrderFormRepository;

	@Autowired
	private ProvideCommodityRepository provideCommodityRepository;

	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;

	@Autowired
	private OperatorDepartmentRepository operatorDepartmentRepository;

	@Autowired
	private OperatorRoleRepository operatorRoleRepository;

	@Autowired
	private OperatorMailConfigRepository operatorMailConfigRepository;

	@Autowired
	private OperatorCodeRepository operatorCodeRepository;

	@Autowired
	private OperatorQueryMailRecordRepository operatorQueryMailRecordRepository;

	@Autowired
	private OperatorRoleUserRepository operatorRoleUserRepository;

	@Autowired
	private OperatorScreenUsersRepository operatorScreenUsersRepository;

	@Autowired
	private OperatorSyspageRepository operatorSyspageRepository;

	@Autowired
	private OperatorProviderOrderDao operatorProviderOrderDao;
	
	@Autowired
	private PersonalUserCouponRepository personalUserCouponRepository;

	@PersistenceContext
	private EntityManager manager;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	public OperatorUserService(OperatorUserRepository operatorUserRepository,
			OperatorSendCodeService operatorSendCodeService) {
		this.operatorUserRepository = operatorUserRepository;
		this.operatorSendCodeService = operatorSendCodeService;
	}

	public OperatorUserRepository getProvideUserRepository() {
		return operatorUserRepository;
	}

	public OperatorSendCodeService getOperatorSendCodeService() {
		return operatorSendCodeService;
	}

	@Override
	public Optional<OperatorUser> getByUsername(String username) {
		return this.operatorUserRepository.findByUsername(username);
	}

	@Override
	public OperatorUser operatorLogin(String username, String password) {

		return this.operatorUserRepository.operatorLogin(username, password);
	}

	public List<OperatorSyspage> selectById(String pids) {
		List<OperatorSyspage> lists = null;
		if (StringUtils.isNotEmpty(pids)) {
			if (pids.contains(",")) {
				String[] commoditySs = pids.split(",");
				List twoIdList = new ArrayList();
				Collections.addAll(twoIdList, commoditySs);
				lists = operatorSyspageRepository.findBysidIn(twoIdList);
			}
		}
		return lists;
	}

	public int savepid(String name) {

		OperatorSyspage operatorSyspage = new OperatorSyspage();
		operatorSyspage.setPid(name);
		operatorSyspageRepository.save(operatorSyspage);
		return 1;
	}

	public OperatorSyspage getRoot() {
		OperatorSyspage operatorSyspage = operatorSyspageRepository.findOne("297e58705e47a882015e47d37df70000");
		operatorSyspage.setOperatorSyspagelist(this.findByParentId(operatorSyspage.getId()));
		return operatorSyspage;
	}

	public List<OperatorSyspage> findByParentId(String pid) {
		List<OperatorSyspage> list = operatorSyspageRepository.findByPid(pid);
		if (list != null && list.size() > 0) {
			for (OperatorSyspage operatorSyspage : list) {
				operatorSyspage.setOperatorSyspagelist(this.findByParentId(operatorSyspage.getId()));
			}
		}
		return list;
	}

	/**
	 * 
	 * @Description: 验证用户名密码 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return ReturnResult    @throws 
	 */
	@Transactional
	public Map<String, Object> validatUandP(String username, String password) {
		ReturnResult returnResult = new ReturnResult();
		Map<String, Object> map = new HashMap<>();
		List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(username);
		if (operUserList != null && operUserList.size() > 0) {
			OperatorUser operatorUser = operUserList.get(0);
			if (operatorUser.getPassword() != null && (!operatorUser.getPassword().equals(""))) {
				if (operatorUser.getPassword().equals(password)) {
					OperatorUser operatorUser1 = operatorUserRepository.operatorLogin(username, password);
					if (operatorUser1 != null) {
						// 登录状态正常
						if (operatorUser.getStatus() == 0) {

							// 登录后分配权限
							if (operatorUser.getRoleId() != null && !operatorUser.getRoleId().equals("")) {
								OperatorRole operatorRole = operatorRoleRepository.findOne(operatorUser.getRoleId());
								if (operatorRole != null) {
									String pids = operatorRole.getPids();
									if (!pids.equals("")) {
										OperatorSyspage operatorSyspage = getRoot();
										map.put("syspage", operatorSyspage);
										map.put("pid", pids);
										map.put("username", operatorUser.getUsername());
										map.put("rolename", operatorRole.getRolename());
										map.put("departmentId", operatorUser.getDepartmentId());
										map.put("id", operatorUser.getId());
										map.put("status", 1);
										request.getSession().setAttribute("opsysUser", operatorUser);

									}
								}
							} else {
								map.put("error", "该账号没有权限");
								map.put("status", 2);
							}
							
							// 未激活
						} else if (operatorUser.getStatus() == 1) {
							map.put("error", "未激活");
							map.put("status", 3);
							
							// 该账号被冻结
						} else if (operatorUser.getStatus() == 9) {
							map.put("error", "该账号被冻结");
							map.put("status", 4);
							
							// 账号被封禁
						} else if (operatorUser.getStatus() == 99) {
							map.put("error", "账号被封禁");
							map.put("status", 5);
							
						}
					}
				} else {
					map.put("error", "密码错误");
					map.put("status", 6);
					
				}
			} else {
				map.put("error", "密码错误");
				map.put("status", 6);
				
			}

		} else {
			map.put("error", "请联系管理员，创建账号");
			map.put("status", 7);

			
		}

		return map;
	}

	/**
	 * 
	 * @param telephone
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public ReturnResult sendVeryMessage(String account) throws Exception {
		ReturnResult returnResult = new ReturnResult();
		List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(account);
		if (operUserList.size() > 0) {
			if (operUserList.get(0).getUserPhone() != null && operUserList.get(0).getName() != null) {
				returnResult = operatorSendCodeService.sendCode(operUserList.get(0).getName(),
						operUserList.get(0).getUserPhone());
			} else {
				if(operUserList.get(0).getUsername().equals("admin")){
					returnResult.setKey("202");
					returnResult.setValue("您是超级管理员,想修改新密码,请到账号设置中编辑手机号和姓名!");
				}else{
					returnResult.setKey("201");
					returnResult.setValue("名字手机号为空");
				}
			}
		} else {
				returnResult.setKey("203");
				returnResult.setValue("用户不存在");
		}
		return returnResult;
	}

	/**
	 * 
	 * @param telephone
	 * @param password
	 * @return
	 */
	@Transactional
	public ReturnResult forgetPassword(String username, String password) {
		ReturnResult returnResult = new ReturnResult();
		List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(username);
		OperatorUser operatorUser = null;
		if (operUserList.size() > 0) {
			operatorUser = operUserList.get(0);
			operatorUser.setPassword(password);
			operatorUserRepository.save(operatorUser);
			returnResult.setKey("success");
			returnResult.setValue("设置密码成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("用户不存在");
		}
		return returnResult;

	}

	public ReturnResult validateUsernameIs(String username) {

		ReturnResult returnResult = new ReturnResult();
		List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(username);
		if (operUserList.size() == 0) {
			returnResult.setKey("error");
			returnResult.setValue("用户不存在");
		} else {
			returnResult.setKey("success");
			returnResult.setValue("验证成功");
		}
		return returnResult;

	}

	// 获取6位随机数字
	public static String getSixCode() {
		// 数组，用于存放随机字符
		char[] chArr = new char[6];
		// 为了保证必须包含数字、大小写字母
		chArr[0] = (char) ('0' + StdRandom.uniform(0, 10));
		chArr[1] = (char) ('A' + StdRandom.uniform(0, 26));
		chArr[2] = (char) ('a' + StdRandom.uniform(0, 26));
		char[] codes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
				'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
				'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
				'z' };
		// charArr[3..len-1]随机生成codes中的字符
		for (int i = 3; i < 6; i++) {
			chArr[i] = codes[StdRandom.uniform(0, codes.length)];
		}

		// 将数组chArr随机排序
		for (int i = 0; i < 6; i++) {
			int r = i + StdRandom.uniform(6 - i);
			char temp = chArr[i];
			chArr[i] = chArr[r];
			chArr[r] = temp;
		}

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < chArr.length; i++) {
			sb.append(chArr[i]);
		}
		String s = sb.toString();

		return s;
	}

	public OperatorUser queryOperatorUserinfo(String id) {
		return operatorUserRepository.findOne(id);

	}

	/**
	 * 
	 * @param name
	 *            姓名
	 * @param userPhone
	 *            手机号
	 * @param depId
	 *            部门Id
	 * @param roleId
	 *            角色ID
	 * @param username
	 *            账号
	 * @return
	 */
	@Transactional
	public ReturnResult saveOpSysuer(String name, String userPhone, String depId, String roleId, String username) {
		ReturnResult returnResult = new ReturnResult();
		OperatorUser operatorUser = new OperatorUser();
		if (depId != null && roleId != null) {
			List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(username);
			if (operUserList.size() > 0) {
				returnResult.setKey("error");
				returnResult.setValue("账号已存在");
			} else {
				List<OperatorUser> list = operatorUserRepository.operatorByPhone(userPhone);
				if (list.size() > 0) {
					returnResult.setKey("error");
					returnResult.setValue("手机号已存在");
				} else {
					operatorUser.setCreateDate(new Date());
					operatorUser.setName(name);
					String pwd = getSixCode();
					operatorUser.setPassword(pwd);
					operatorUser.setStatus(0);
					operatorUser.setUsername(username);
					operatorUser.setUserPhone(userPhone);
					operatorUser.setDepartmentId(depId);
					operatorUser.setRoleId(roleId);
					operatorUserRepository.save(operatorUser);
					try {
						returnResult = operatorSendCodeService.sendCodeforAddAccount(name, pwd, userPhone, username);
					} catch (Exception e) {
						e.printStackTrace();
					}
					/*OperatorRoleUser operatorRoleUser = new OperatorRoleUser();
					operatorRoleUser.setRoleid(roleId);
					operatorRoleUser.setUserid(operatorUser.getId());
					operatorRoleUserRepository.save(operatorRoleUser);*/
					returnResult.setKey("success");
					returnResult.setValue("保存成功");
				}
			}
		} else {
			returnResult.setKey("error");
			returnResult.setValue("请给账号分配部门和角色");
		}
		return returnResult;

	}

	@Transactional
	public ReturnResult editOpSysuer(String id, String name, String userPhone, String depId, String roleId,
			String username, Integer status) {
		ReturnResult returnResult = new ReturnResult();
		if (depId != null) {
			OperatorUser operatorUser = operatorUserRepository.findOne(id);
			if (operatorUser != null) {
				if (userPhone != null && !userPhone.equals("")) {
					if (operatorUser.getUserPhone()!=null&&operatorUser.getUserPhone().equals(userPhone)) {
						operatorUser.setCreateDate(new Date());
						operatorUser.setName(name);
						operatorUser.setUserPhone(userPhone);
						operatorUser.setDepartmentId(depId);
						operatorUser.setRoleId(roleId);
						operatorUser.setStatus(status);
						// operatorUser.setUsername(username);
						operatorUserRepository.saveAndFlush(operatorUser);
						returnResult.setKey("success");
						returnResult.setValue("修改成功");
					} else {
						List<OperatorUser> list = operatorUserRepository.operatorByPhone(userPhone);
						if (list.size() > 0) {
							returnResult.setKey("error");
							returnResult.setValue("手机号已存在");
						} else {
							operatorUser.setCreateDate(new Date());
							operatorUser.setName(name);
							operatorUser.setUserPhone(userPhone);
							operatorUser.setDepartmentId(depId);
							operatorUser.setRoleId(roleId);
							operatorUser.setStatus(status);
							// operatorUser.setUsername(username);
							operatorUserRepository.saveAndFlush(operatorUser);
							returnResult.setKey("success");
							returnResult.setValue("修改成功");
						}
					}

				}

			} else {
				returnResult.setKey("eror");
				returnResult.setValue("修改失败");
			}
		} else {
			returnResult.setKey("error");
			returnResult.setValue("请给账号分配部门");
		}

		return returnResult;
	}

	/**
	 * 
	 * @param ids
	 *            字符串id
	 * @return
	 */
	@Transactional
	public ReturnResult deleteForOpuser(String ids) {
		ReturnResult returnResult = new ReturnResult();
		String[] str = StringUtil.StrList(ids);
		List<OperatorUser> lists = new ArrayList<>();
		String id = "";
		OperatorUser operatorUser = null;
		for (int i = 0; i < str.length; i++) {
			operatorUser = new OperatorUser();
			id = str[i];
			operatorUser.setId(id);
			lists.add(operatorUser);
		}
		operatorUserRepository.delete(lists);
		returnResult.setKey("success");
		returnResult.setValue("删除成功");
		return returnResult;
	}

	/**
	 * 冻结账号
	 * 
	 * @param id
	 * @return
	 */
	@Transactional
	public ReturnResult freezeAcconut(String ids) {
		ReturnResult returnResult = new ReturnResult();
		String[] str = StringUtil.StrList(ids);
		String id = "";
		for (int i = 0; i < str.length; i++) {
			id = str[i];
			OperatorUser operatorUser = operatorUserRepository.findOne(id);
			if (operatorUser != null && operatorUser.getStatus() != 9) {
				operatorUser.setStatus(9);
				operatorUserRepository.save(operatorUser);
			}
		}
		returnResult.setKey("success");
		returnResult.setValue("冻结账号成功");
		return returnResult;
	}

	/**
	 * 激活账号
	 */
	@Transactional
	public ReturnResult activationAcconut(String ids) {
		ReturnResult returnResult = new ReturnResult();
		String[] str = StringUtil.StrList(ids);
		String id = "";
		for (int i = 0; i < str.length; i++) {
			id = str[i];
			OperatorUser operatorUser = operatorUserRepository.findOne(id);
			if (operatorUser != null && operatorUser.getStatus() != 0) {
				operatorUser.setStatus(0);
				operatorUserRepository.save(operatorUser);
			}
		}
		returnResult.setKey("success");
		returnResult.setValue("激活成功");
		return returnResult;

	}

	@Transactional
	public ReturnResult resetPwd(String id) {
		ReturnResult returnResult = new ReturnResult();
		OperatorUser operatorUser = operatorUserRepository.findOne(id);
		if (operatorUser != null) {
			if((operatorUser.getUserPhone()!=null&&!operatorUser.getUserPhone().equals(""))&&(operatorUser.getName()!=null&&!operatorUser.getName().equals(""))
					&&(operatorUser.getUsername()!=null&&!operatorUser.getUsername().equals(""))){
				String pwd = getSixCode();
				try {
					returnResult = operatorSendCodeService.sendCodeforAddAccount(operatorUser.getName(), pwd,
							operatorUser.getUserPhone(), operatorUser.getUsername());
				} catch (Exception e) {
					e.printStackTrace();
				}
				operatorUser.setPassword(pwd);
				operatorUserRepository.save(operatorUser);
				returnResult.setKey("success");
				returnResult.setValue("重置成功");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("手机号，姓名，账号信息不全");
			}
		} else {
			returnResult.setKey("error");
			returnResult.setValue("重置失败");
		}
		return returnResult;
	}

	@Transactional
	public Workbook exportAccountInfos(String ids) {

		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("账号信息");
		Row header = sheet.createRow(0);
		header.createCell(0).setCellValue("账号");
		header.createCell(1).setCellValue("姓名");
		header.createCell(2).setCellValue("联系方式");
		header.createCell(3).setCellValue("所属部门");
		header.createCell(4).setCellValue("用户角色");
		header.createCell(5).setCellValue("账号状态");
		List<OperatorUser> lists = operatorUserRepository.findAll();
		OperatorUser operatorUser = new OperatorUser();
		String[] pids = ids.split(",");
		for (int i = 0; i < lists.size(); i++) {
			operatorUser = lists.get(i);
			for (int j = 0; j < pids.length; j++) {
				String id = pids[j];
				if (id.equals(operatorUser.getId())) {
					Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
					dataRow.createCell(0)
							.setCellValue(operatorUser.getUsername() != null ? operatorUser.getUsername() : "");
					dataRow.createCell(1)
							.setCellValue(operatorUser.getName() != null ? operatorUser.getUsername() : "");
					dataRow.createCell(2)
							.setCellValue(operatorUser.getUserPhone() != null ? operatorUser.getUsername() : "");
					if (operatorUser.getDepartmentId() != null) {
						OperatorDepartment operatorDepartment = operatorDepartmentRepository
								.findOne(operatorUser.getDepartmentId());
						if (operatorDepartment != null) {
							dataRow.createCell(3).setCellValue(
									operatorUser.getUsername() != null ? operatorDepartment.getDepname() : "");
						}
					}
					if (operatorUser.getRoleId() != null) {
						OperatorRole operatorRole = operatorRoleRepository.findOne(operatorUser.getRoleId());
						dataRow.createCell(4)
								.setCellValue(operatorUser.getRoleId() != null ? operatorRole.getRolename() : "");
					}
					// 0---正常 1---未激活 9---冻结 99---封禁
					if (operatorUser.getStatus() != null) {
						if (operatorUser.getStatus() == 0) {
							dataRow.createCell(5).setCellValue("正常");
						} else if (operatorUser.getStatus() == 1) {
							dataRow.createCell(5).setCellValue("未激活");
						} else if (operatorUser.getStatus() == 9) {
							dataRow.createCell(5).setCellValue("冻结");
						} else if (operatorUser.getStatus() == 99) {
							dataRow.createCell(5).setCellValue("封禁");
						}
					}
				}

			}

		}
		return wb;
	}

	public Page<OperatorUser> multiconditionQuery(Integer page, Integer size, String name, String phone, Integer status,
			String depId, String roleId) {
		Specification<OperatorUser> specification = new Specification<OperatorUser>() {
			@Override
			public Predicate toPredicate(Root<OperatorUser> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				if (name != null && !name.equals("")) {
					lstPredicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+name+"%"));
				}
				if (phone != null && !phone.equals("")) {
					lstPredicates.add(criteriaBuilder.like(root.get("userPhone").as(String.class), "%"+phone+"%"));
				}
				if (status != null) {
					lstPredicates.add(criteriaBuilder.equal(root.get("status"), status));
				}
				if (depId != null && !depId.equals("")) {
					lstPredicates.add(criteriaBuilder.equal(root.get("departmentId"), depId));
				}
				if (roleId != null && !roleId.equals("")) {
					lstPredicates.add(criteriaBuilder.equal(root.get("roleId"), roleId));
				}
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		Sort sort = new Sort(Sort.Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		Page<OperatorUser> list = operatorUserRepository.findAll(specification, pageable);
		if (list.getContent().size() > 0) {
			for (OperatorUser operatorUser : list.getContent()) {
				if (operatorUser.getDepartmentId() != null) {
					OperatorDepartment operatorDepartment = operatorDepartmentRepository
							.findOne(operatorUser.getDepartmentId());

					if (operatorDepartment != null) {
						operatorUser.setDepname(operatorDepartment.getDepname());
					}
				}
				if (operatorUser.getRoleId() != null) {
					OperatorRole operatorRole = operatorRoleRepository.findOne(operatorUser.getRoleId());
					if (operatorRole != null) {
						operatorUser.setRolename(operatorRole.getRolename());
					}
				}
			}
			return list;
		}
		return null;
	}

	/**
	 * 
	 */
	public Page<OperatorUser> operatorUserList(Integer page, Integer size) {
		Page<OperatorUser> lists = operatorUserRepository.findAll(new PageRequest(page, size));
		if (lists.getContent().size() > 0) {
			for (OperatorUser operatorUser : lists.getContent()) {
				operatorUser.setRoles(null);
				OperatorDepartment operatorDepartment = operatorDepartmentRepository
						.findOne(operatorUser.getDepartmentId());
				if (operatorDepartment.getDepname() != null) {
					operatorUser.setDepartmentId(operatorDepartment.getDepname());
				}
				OperatorRole operatorRole = operatorRoleRepository.findOne(operatorUser.getRoleId());
				if (operatorRole.getRolename() != null) {
					operatorUser.setRoleId(operatorRole.getRolename());
				}
			}
			return lists;
		}
		return null;
	}

	public Map<String, Object> selectUserInfos(Integer page, Integer size) {
		Map<String, Object> map = operatorUserInfoDao.selectUserinfosPage(page, size);
		List<OperatorUserRo> list = (List<OperatorUserRo>) map.get("result");
		OperatorUserRo operatorUserRo = new OperatorUserRo();
		for (int i = 0; i < list.size(); i++) {
			operatorUserRo = list.get(i);
			PersonalUser personalUser = personalUserRepository.findOne(operatorUserRo.getId());
			if (personalUser != null) {
				if (personalUser.getIsProvider().equals("2")) {
					operatorUserRo.setAssociatCompany("已认证");
				} else {
					operatorUserRo.setAssociatCompany("未认证");
				}
				// 交易金额
				List<ProvideCommodity> prcs = provideCommodityRepository.selectByCommodityUser(operatorUserRo.getId());
				Double sumPrice = 0.0;// 交易金额
				Double closing = 0.0;
				int volume = 0;// 成交量
				int sumvolume = 0; // 生成订单总数
				for (ProvideCommodity provideCommodity : prcs) {
					Double shangpinPrice = 0.0;
					int volumeuniq = 0;
					int vo = 0;
					List<ProvideOrderForm> pofs = provideOrderFormRepository
							.selectBycommodity(provideCommodity.getId());
					if (pofs.size() > 0) {
						shangpinPrice = provideOrderFormRepository.selectSumrRate(provideCommodity.getId());
						if (shangpinPrice == 0.0) {
							shangpinPrice = 0.0;
						}
					}
					volumeuniq = provideOrderFormRepository.selectBycountvolume(provideCommodity.getId());
					vo = provideOrderFormRepository.selectBycountTotalOrder(provideCommodity.getId());
					sumvolume += vo;
					sumPrice += shangpinPrice;
					volume += volumeuniq;
				}
				operatorUserRo.setTransactionAmount(sumPrice);
				operatorUserRo.setRelease(volume);
				// 成交率(成交量/生成订单总数)
				// 成交量：成交笔数完成 成交是以最终客户确认，订单全部关闭为准
				// 生成订单总数：平台生成的订单量（订单总数）
				String str_i = Integer.toString(volume);
				String str_j = Integer.toString(sumvolume);
				if (volume == 0 || volume == 0 && sumvolume == 0) {
					operatorUserRo.setClosing(0.0);
				} else {
					operatorUserRo.setClosing(Double.valueOf(str_i) / Double.valueOf(str_j));
				}
			}
		}
		return map;
	}

	@Transactional
	public Workbook exportUserInfos(String ids) {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("用户信息");
		Row header = sheet.createRow(0);
		header.createCell(0).setCellValue("账号");
		header.createCell(1).setCellValue("注册时间");
		header.createCell(2).setCellValue("成交笔数");
		header.createCell(3).setCellValue("成交金额");
		header.createCell(4).setCellValue("成交率");
		header.createCell(5).setCellValue("关联企业");
		header.createCell(6).setCellValue("状态");
		List<OperatorUserRo> list = selectUserNopageInfos(null, null);
		String[] pids = ids.split(",");
		OperatorUserRo operatorUserRo = new OperatorUserRo();
		for (int i = 0; i < list.size(); i++) {
			operatorUserRo = list.get(i);
			for (int j = 0; j < pids.length; j++) {
				String id = pids[j];
				if (id.equals(operatorUserRo.getId())) {
					Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
					if (operatorUserRo.getUsername() != null) {
						dataRow.createCell(0).setCellValue(operatorUserRo.getUsername());
					} else {
						dataRow.createCell(0).setCellValue("");
					}
					if (operatorUserRo.getCreateTime() != null) {
						dataRow.createCell(1).setCellValue(operatorUserRo.getCreateTime());
					} else {
						dataRow.createCell(1).setCellValue("");
					}
					if (operatorUserRo.getRelease() != null) {
						dataRow.createCell(2).setCellValue(operatorUserRo.getRelease());
					} else {
						dataRow.createCell(2).setCellValue("");
					}
					dataRow.createCell(3).setCellValue(
							operatorUserRo.getTransactionAmount() != null ? operatorUserRo.getTransactionAmount() : 0);
					dataRow.createCell(4)
							.setCellValue(operatorUserRo.getClosing() != null ? operatorUserRo.getClosing() : 0);
					dataRow.createCell(5).setCellValue(
							operatorUserRo.getAssociatCompany() != null ? operatorUserRo.getAssociatCompany() : "");
					dataRow.createCell(6)
							.setCellValue(operatorUserRo.getIsProvider() != null ? operatorUserRo.getIsProvider() : "");
				}
			}
		}
		return wb;
	}
	
	
	
	public Workbook exportAlluserInfos(String starttime,String endtime) {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("用户信息");
		Row header = sheet.createRow(0);
		header.createCell(0).setCellValue("编号");
		header.createCell(1).setCellValue("账号");
		header.createCell(2).setCellValue("注册时间");
		header.createCell(3).setCellValue("成交笔数");
		header.createCell(4).setCellValue("成交金额");
		header.createCell(5).setCellValue("成交率");
		header.createCell(6).setCellValue("关联企业");
		header.createCell(7).setCellValue("邀请人");
		header.createCell(8).setCellValue("状态");
		List<Personelinfo> list = selectByAllAccountforUser(starttime, endtime);
		if(list.size()>0){
			Personelinfo operatorUserRo = new Personelinfo();
			for (int i = 0; i < list.size(); i++) {
				operatorUserRo = list.get(i);
				Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
				dataRow.createCell(0).setCellValue(i+1);
				dataRow.createCell(1).setCellValue(operatorUserRo.getUsername()!=null?operatorUserRo.getUsername():"");
				if(operatorUserRo.getCreateTime()!=null&&!operatorUserRo.getCreateTime().equals("")){
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ");
			    	String ss=	sdf.format(operatorUserRo.getCreateTime()); 
					dataRow.createCell(2).setCellValue(ss);
				}else{
					dataRow.createCell(2).setCellValue("");
				}
				dataRow.createCell(3).setCellValue(operatorUserRo.getReleasenum()!=null?operatorUserRo.getReleasenum():0);
				dataRow.createCell(4).setCellValue(operatorUserRo.getTransactionAmount()!=null?operatorUserRo.getTransactionAmount():0);
				if(operatorUserRo.getClosing()!=null){
					DecimalFormat df = new DecimalFormat("0.00%");
					String r = df.format(operatorUserRo.getClosing());
					dataRow.createCell(5).setCellValue(r);
				}else{
					dataRow.createCell(5).setCellValue("");
					
				}
				if(operatorUserRo.getIsProvider()!=null){
					if(operatorUserRo.getIsProvider().equals("2")){
						dataRow.createCell(6).setCellValue("已认证");
					}else{
						dataRow.createCell(6).setCellValue("未认证");
					}
				}else{
					dataRow.createCell(6).setCellValue("未认证");
				}
				dataRow.createCell(7).setCellValue(operatorUserRo.getRecusername()!=null?operatorUserRo.getRecusername():"");
				if(operatorUserRo.getIsFreeze()!=null){
					if(operatorUserRo.getIsFreeze().equals("1")){
						dataRow.createCell(8).setCellValue("冻结");
					}else  if(operatorUserRo.getIsFreeze().equals("")||operatorUserRo.getIsFreeze()!="1"){
						dataRow.createCell(8).setCellValue("正常");
					}
				}else{
					dataRow.createCell(8).setCellValue("正常");
				}
				
			}	
		}
		
		return wb;
	}
	
	
	
	
	
	
	

	public List<OperatorUserRo> selectUserNopageInfos(Integer page, Integer size) {
		List<OperatorUserRo> list = null;
		if (page != null && size != null) {
			Map<String, Object> map = operatorUserInfoDao.selectUserinfosPage(page, size);
			list = (List<OperatorUserRo>) map.get("result");
		} else {
			list = operatorUserInfoDao.selectUserinfos();
		}
		OperatorUserRo operatorUserRo = new OperatorUserRo();
		for (int i = 0; i < list.size(); i++) {
			operatorUserRo = list.get(i);
			PersonalUser personalUser = personalUserRepository.findOne(operatorUserRo.getId());
			if (personalUser != null) {
				if (personalUser.getIsProvider().equals("2")) {
					operatorUserRo.setAssociatCompany("已认证");
				} else {
					operatorUserRo.setAssociatCompany("未认证");
				}
				// 交易金额
				List<ProvideCommodity> prcs = provideCommodityRepository.selectByCommodityUser(operatorUserRo.getId());
				Double sumPrice = 0.0;// 交易金额
				Double closing = 0.0;
				int volume = 0;// 成交量
				int sumvolume = 0; // 生成订单总数
				for (ProvideCommodity provideCommodity : prcs) {
					Double shangpinPrice = 0.0;
					int volumeuniq = 0;
					int vo = 0;
					List<ProvideOrderForm> pofs = provideOrderFormRepository
							.selectBycommodity(provideCommodity.getId());
					if (pofs.size() > 0) {
						shangpinPrice = provideOrderFormRepository.selectSumrRate(provideCommodity.getId());
						if (shangpinPrice == 0.0) {
							shangpinPrice = 0.0;
						}
					}
					volumeuniq = provideOrderFormRepository.selectBycountvolume(provideCommodity.getId());
					vo = provideOrderFormRepository.selectBycountTotalOrder(provideCommodity.getId());
					sumvolume += vo;
					sumPrice += shangpinPrice;
					volume += volumeuniq;
				}
				operatorUserRo.setTransactionAmount(sumPrice);
				operatorUserRo.setRelease(volume);
				// 成交率(成交量/生成订单总数)
				// 成交量：成交笔数完成 成交是以最终客户确认，订单全部关闭为准
				// 生成订单总数：平台生成的订单量（订单总数）
				String str_i = Integer.toString(volume);
				String str_j = Integer.toString(sumvolume);
				if (volume == 0 || volume == 0 && sumvolume == 0) {
					operatorUserRo.setClosing(0.0);
				} else {
					operatorUserRo.setClosing(Double.valueOf(str_i) / Double.valueOf(str_j));
				}
			}
		}
		return list;
	}

	@Transactional
	public OperatorBusinessAndUser viewmerchantinfo(String id) {
		OperatorBusinessAndUser operatorBusinessAndUser = new OperatorBusinessAndUser();
		PersonalUser personalUser = personalUserRepository.findOne(id);
		if (personalUser != null) {
			// -------------账号基本信息
			operatorBusinessAndUser.setPortrait(personalUser.getPortrait());
			// 账号
			operatorBusinessAndUser.setUsername(personalUser.getUsername());
			// 姓名
			operatorBusinessAndUser.setName(personalUser.getName());
			// 注册时间
			operatorBusinessAndUser.setCreateTime(personalUser.getCreateTime());
			// 邮箱
			operatorBusinessAndUser.setEmail(personalUser.getEmail());
			// 微信
			operatorBusinessAndUser.setWechat(personalUser.getWechat());
			// 微博
			operatorBusinessAndUser.setWeibo(personalUser.getWeibo());
			// 服务商
			operatorBusinessAndUser.setIsProvider(personalUser.getIsProvider());
			// 账号状态
			operatorBusinessAndUser.setAccountstatus(personalUser.getIsFreeze());
			operatorBusinessAndUser.setCreateType(personalUser.getCreateType());
			// -------------企业基本信息
			List<ProviderBusiness> providerBusiness = providerBusinessRepository.viewmerUchantinfo(id);
			if (providerBusiness.size() > 0) {
				// 企业名称
				operatorBusinessAndUser.setCompanyName(providerBusiness.get(0).getCompanyName());
				// 行业
				operatorBusinessAndUser.setCompanyindustry(providerBusiness.get(0).getCompanyindustry());
				// 证件
				operatorBusinessAndUser.setCompanyResgiserMark(providerBusiness.get(0).getCompanyResgiserMark());
				// 企业联系人
				operatorBusinessAndUser.setCompanyCorporationName(providerBusiness.get(0).getCompanyCorporationName());
				// 公司地址
				operatorBusinessAndUser.setCompanyAdress(providerBusiness.get(0).getCompanyAdress());
				// 成立时间
				operatorBusinessAndUser.setCompanyRegistTime(providerBusiness.get(0).getCompanyRegistTime());
				// 注册资本
				operatorBusinessAndUser
						.setCompanyRegisteredCapital(providerBusiness.get(0).getCompanyRegisteredCapital());
				// 企业规模
				operatorBusinessAndUser.setCompanyEnterpriseScale(providerBusiness.get(0).getCompanyEnterpriseScale());
				// 企业邮箱
				operatorBusinessAndUser.setCompanyEmail(providerBusiness.get(0).getCompanyEmail());
				// 前台电话
				operatorBusinessAndUser.setCompanyfrontDeskphone(providerBusiness.get(0).getCompanyfrontDeskphone());
				// 微信公众号
				operatorBusinessAndUser.setCompanyWeChatpublic(providerBusiness.get(0).getCompanyWeChatpublic());
				// 公司标记
				operatorBusinessAndUser.setCompanytag(providerBusiness.get(0).getCompanytag());
				// 服务范围

				operatorBusinessAndUser.setCompanyLicenseReplica(providerBusiness.get(0).getCompanyLicenseReplica());
				// 公司描述
				operatorBusinessAndUser.setCompanyIntroduce(providerBusiness.get(0).getCompanyIntroduce());
				operatorBusinessAndUser.setBusinessName(providerBusiness.get(0).getBusinessName());
				
				operatorBusinessAndUser.setVoucherType(providerBusiness.get(0).getVoucherType());
				operatorBusinessAndUser.setCompanyCorporationName(providerBusiness.get(0).getCompanyCorporationName());
				operatorBusinessAndUser.setCompanyCorporationIDCardNo(providerBusiness.get(0).getCompanyCorporationIDCardNo());
				operatorBusinessAndUser.setCompanyCorporationIDCardNoFront(providerBusiness.get(0).getCompanyCorporationIDCardNoFront());
				operatorBusinessAndUser.setCompanyCorporationIDCardNoContrary(providerBusiness.get(0).getCompanyCorporationIDCardNoContrary());
				
			}

		}
		return operatorBusinessAndUser;

	}

	/**
	 * 
	 * @param id
	 *            用户ID
	 * @param status
	 *            0--》消费 和 1--》接单
	 * @return
	 */
	public Map<String, Object> tradingInfo(String id, Integer status) {
		// List<Orderforbusiness> arr = new ArrayList<>();
		List<Orderforbusiness> arr1 = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		Double consumption = 0.0;
		Integer number = 0;
		Integer closingnumber = 0;
		Integer singledispute = 0;
		Double consumption1 = 0.0;
		Integer number1 = 0;
		Integer closingnumber1 = 0;
		Integer singledispute1 = 0;
		if (status == 1) {
			List<Orderforbusiness> listofs = operatorProviderOrderDao.selectByid(id);

			map.put("consumptionlist", listofs);// 订单列表
			if (listofs.size() > 0) {
				consumption = provideOrderFormRepository.selectuserSumrRate1(id);
				if (consumption == null) {
					consumption = 0.0;
				}
			}
			map.put("consumption", consumption);// 消费
			map.put("status", 1);// 消费
			number = provideOrderFormRepository.selectByordernumber(id);
			map.put("ordernumber", number);// 下单笔数
			closingnumber = provideOrderFormRepository.selectsucordernumber(id);
			map.put("closingnumber", closingnumber);// 下单成功
			singledispute = provideOrderFormRepository.selectSingledisputenum(id);
			map.put("singledispute", singledispute);// 纠纷单
		}
		List<Orderforbusiness> listofs2=null;
		//List<Orderforbusiness> arr=new  ArrayList<>();
		if (status == 2) {
			String busid="";
			List<ProviderBusiness> providerBusiness1 = providerBusinessRepository.viewmerUchantinfo(id);
			if (providerBusiness1.size() > 0) {
				//List<ProvideCommodity> pcs1 = operatorProviderOrderDao.selectBycommid(providerBusiness1.get(0).getId());
				//if(pcs1.size()>0){
					//for (ProvideCommodity provideCommodity : pcs1) {
						 listofs2 = operatorProviderOrderDao.selectBycomid(providerBusiness1.get(0).getId());
						/*if(listofs1.size()>0){
							for (Orderforbusiness provideOrderForm : listofs1) {
								arr.add(provideOrderForm);
							}
						}*/
						// 盈收
						Double	consumption2 = provideOrderFormRepository.selectSumrRate(providerBusiness1.get(0).getId());
						if(consumption2==null){
							consumption2=0.0;
						}
						consumption1 += consumption2;
						// 接单笔数
						int	number2 = provideOrderFormRepository.selectBycountTotalOrder(providerBusiness1.get(0).getId());
						number1 += number2;
						// 接单成功
						closingnumber1 = provideOrderFormRepository.selectBycountvolume(providerBusiness1.get(0).getId());
						// 纠纷单、
						int	singledispute2 = provideOrderFormRepository.selectSinglebdisputenum(providerBusiness1.get(0).getId());
						singledispute1 += singledispute2;
					//}
				//}
						busid=providerBusiness1.get(0).getId();
			}
			map.put("busid", busid);
			map.put("consumptionlist1", listofs2);
			map.put("status", 2);// 消费
			map.put("consumption1", consumption1);
			map.put("ordernumber1", number1);// 下单笔数
			map.put("closingnumber1", closingnumber1);
			map.put("singledispute1", singledispute1);// 纠纷单
		}
		// 购买记录
		List<Orderforbusiness> listofs1 = operatorProviderOrderDao.selectByidbuy(id);
		System.out.println(listofs1);
		List<BusinessServer> str = new ArrayList<>();
		for (Orderforbusiness orderforbusiness : listofs1) {
			BusinessServer businessServer = new BusinessServer();
			businessServer.setServername(orderforbusiness.getServerName());
			int num = provideOrderFormRepository.selectBycountOid(id, orderforbusiness.getServerName());
			businessServer.setNum(num);
			str.add(businessServer);
		}
		map.put("businesstype", str);// 业务分类 (购买次数)
		/*
		 * List<ProviderBusiness> providerBusiness =
		 * providerBusinessRepository.viewmerUchantinfo(id);
		 * List<BusinessServer> str = new ArrayList<>();
		 * if(providerBusiness.size()>0){
		 * if(providerBusiness.get(0).getId()!=null){ List<ProvideCommodity> pcs
		 * =
		 * provideCommodityRepository.selectByCommodity(providerBusiness.get(0).
		 * getId()); int num = 0; if (pcs.size() > 0) { for (ProvideCommodity
		 * provideCommodity : pcs) { BusinessServer businessServer = new
		 * BusinessServer();
		 * businessServer.setServername(provideCommodity.getServiceType().
		 * getServerName()); num =
		 * provideOrderFormRepository.selectBycountTotalOrder(provideCommodity.
		 * getId()); businessServer.setNum(num); str.add(businessServer); } } }
		 * } map.put("businesstype", str);// 业务分类 (购买次数)
		 */
		return map;
	}

	@Transactional
	public ReturnResult editUsercomInfo(String id, ProviderBusiness providerBusiness) throws UnsupportedEncodingException {
		ReturnResult returnResult = new ReturnResult();
		List<ProviderBusiness> bu = providerBusinessRepository.viewmerUchantinfo(id);
		if (bu.size()>0) {
			bu.get(0).setBusinessName(providerBusiness.getBusinessName());
			bu.get(0).setCompanyName(providerBusiness.getCompanyName());
			bu.get(0).setCompanyLicenseReplica(providerBusiness.getCompanyLicenseReplica());
			bu.get(0).setCompanyindustry(providerBusiness.getCompanyindustry());
			bu.get(0).setCompanyRegistTime(providerBusiness.getCompanyRegistTime());
			bu.get(0).setCompanyRegisteredCapital(providerBusiness.getCompanyRegisteredCapital());
			bu.get(0).setCompanyfrontDeskphone(providerBusiness.getCompanyfrontDeskphone());
			bu.get(0).setCompanyEmail(providerBusiness.getCompanyEmail());
			bu.get(0).setCompanyEnterpriseScale(providerBusiness.getCompanyEnterpriseScale());
			bu.get(0).setCompanyWeChatpublic(providerBusiness.getCompanyWeChatpublic());
			bu.get(0).setCompanyIntroduce(providerBusiness.getCompanyIntroduce());
			bu.get(0).setCompanyAdress(providerBusiness.getCompanyAdress());
				if((providerBusiness.getCompanyName()!=null&&!providerBusiness.getCompanyName().equals(""))
						||(providerBusiness.getBusinessName()!=null&&!providerBusiness.getBusinessName().equals(""))){
					// 平台描述为10
					String flag = validateBusiness1(10,providerBusiness.getBusinessName(),
							 providerBusiness.getCompanyName(),bu.get(0).getId());
					if (flag.equals("SUCCESS")) {
						System.out.println("编辑成功");
					}
					
				}
			providerBusinessRepository.save(bu);
			returnResult.setKey("success");
			returnResult.setValue("保存成功");
		} else {
			ProviderBusiness  providerBusiness1=new ProviderBusiness();
			providerBusiness1.setCompanyName(providerBusiness.getCompanyName());                           
			providerBusiness1.setBusinessName(providerBusiness.getBusinessName());                           
			providerBusiness1.setCompanyLicenseReplica(providerBusiness.getCompanyLicenseReplica());       
			providerBusiness1.setCompanyindustry(providerBusiness.getCompanyindustry());                   
			providerBusiness1.setCompanyRegistTime(providerBusiness.getCompanyRegistTime());               
			providerBusiness1.setCompanyRegisteredCapital(providerBusiness.getCompanyRegisteredCapital()); 
			providerBusiness1.setCompanyfrontDeskphone(providerBusiness.getCompanyfrontDeskphone());       
			providerBusiness1.setCompanyEmail(providerBusiness.getCompanyEmail());                         
			providerBusiness1.setCompanyEnterpriseScale(providerBusiness.getCompanyEnterpriseScale());     
			providerBusiness1.setCompanyWeChatpublic(providerBusiness.getCompanyWeChatpublic());           
			providerBusiness1.setCompanyIntroduce(providerBusiness.getCompanyIntroduce());                 
			providerBusiness1.setCompanyAdress(providerBusiness.getCompanyAdress());   
			providerBusiness1.setServiceRange(1);
			PersonalUser personalUser=new PersonalUser();
			personalUser.setId(id);
			providerBusiness1.setPersonalUser(personalUser);
			providerBusinessRepository.save(providerBusiness1);
			returnResult.setKey("success");
			returnResult.setValue("保存成功");
		}
		return returnResult;
	}

	
	/**
	 * 调外部审核接口
	 * 
	 * @param systemCode
	 *            平台描述
	 * @param companyName
	 *            服务商名称
	 * @param companyTitle
	 *            服务商公司名称
	 * @param originalId
	 *            服务商主键Id
	 * @param comCode    是否为内部服务商1为外部服务商，2为内部服务商
	 *            
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String validateBusiness(Integer systemCode, String companyName, String companyTitle,
			String originalId,Integer comCode) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8")+"&comCode="+comCode;
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}
	/**
	 * 调外部编辑接口
	 * 
	 * @param systemCode
	 *            平台描述
	 * @param companyName
	 *            服务商名称
	 * @param companyTitle
	 *            服务商公司名称
	 * @param originalId
	 *            服务商主键Id
	 * @param comCode    是否为内部服务商1为外部服务商，2为内部服务商
	 *            
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String validateBusiness1(Integer systemCode, String companyName, String companyTitle,
			String originalId) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8");
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}
	

	
	// 比较两个时间相差多少分钟
	public static String getDatePoor(Date endDate, Date nowDate) {

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		// 计算差多少分钟
		long min = diff % nd % nh / nm;

		return min + "";
	}

	/*
	 * @param page 默认为0
	 * 
	 * @param size 每页10条
	 * 
	 * @param acount 商户账号
	 * 
	 * @param status 状态
	 * 
	 * @param volume 成交量
	 * 
	 * @param volumesymbol 成交量符号
	 * 
	 * @param clinchadealAmount 成交金额
	 * 
	 * @param clinchadealAmountsymbol 成交金额符号
	 * 
	 * @param closing 成交率
	 * 
	 * @param closingsymbol 成交率符号
	 * 
	 * @param certification 是否认证
	 * 
	 * @param registStartDate 注册时间（起始时间）
	 * 
	 * @param registEndDate 注册时间(结束时间）
	 * 
	 * @return
	 */

	public Map<String, Object> selectByAccountforUser(Integer page, Integer size, String acount, String status,
			Integer volume, String volumesymbol, Double clinchadealAmount, String clinchadealAmountsymbol,
			Double closing, String closingsymbol, String certification, String registStartDate, String registEndDate,String couponid,
			String recusername) {

		String jpql = "select u from Personelinfo u where 1=1";
		if (StringUtils.isNotEmpty(acount)) {
			jpql += " and u.username like '%" + acount + "%'";
		}
		if (StringUtils.isNotEmpty(recusername)) {
			jpql += " and u.recusername like '%" + recusername + "%'";
		}
		if (StringUtils.isNotEmpty(status)) {
			if (status.equals("正常")) {
				jpql += " and (u.isFreeze != '1' or u.isFreeze is null or u.isFreeze='')";
			} else if (status.equals("冻结")) {
				jpql += " and u.isFreeze = '1'";
			} else if (status.equals("所有")) {

			}
		}
		if (volume != null && (volumesymbol != null && !volumesymbol.equals(""))) {
			if (volumesymbol.equals("大于")) {
				jpql += " and u.releasenum > '" + volume + "'";
			} else if (volumesymbol.equals("等于")) {
				jpql += " and u.releasenum = '" + volume + "'";
			} else if (volumesymbol.equals("小于")) {
				jpql += " and u.releasenum < '" + volume + "'";

			}
		}
		if (clinchadealAmount != null && (clinchadealAmountsymbol != null && !clinchadealAmountsymbol.equals(""))) {
			if (clinchadealAmountsymbol.equals("大于")) {
				jpql += " and u.releasenum > '" + clinchadealAmount + "'";
			} else if (clinchadealAmountsymbol.equals("等于")) {
				jpql += " and u.releasenum = '" + clinchadealAmount + "'";
			} else if (clinchadealAmountsymbol.equals("小于")) {
				jpql += " and u.releasenum < '" + clinchadealAmount + "'";
			}
		}
		if (closing != null && (closingsymbol != null && !closingsymbol.equals(""))) {
			if (closingsymbol.equals("大于")) {
				jpql += " and u.closing > '" + closing + "'";
			} else if (closingsymbol.equals("等于")) {
				jpql += " and u.closing = '" + closing + "'";
			} else if (closingsymbol.equals("小于")) {
				jpql += " and u.closing < '" + closing + "'";
			}
		}
		if (certification != null && !certification.equals("")) {
			if (certification.equals("已认证")) {
				jpql += " and u.isProvider = '2'";
			} else if (certification.equals("未认证")) {
				jpql += " and (u.isProvider != '2' or u.isProvider is null or u.isProvider='')";
			}
		}
		if (registStartDate != null && !registStartDate.equals("")) {

			String datee = registStartDate;
			datee = datee.replace("Z", " UTC");// 注意是空格+UTC
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");// 注意格式化的表达式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date1 = null;
			String str = "";
			try {
				date1 = format.parse(datee);
				str = sdf.format(date1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			jpql += " and u.createTime >='" + str + "'";
		}
		if (registEndDate != null && !registEndDate.equals("")) {
			String datee = registEndDate;
			datee = datee.replace("Z", " UTC");// 注意是空格+UTC
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");// 注意格式化的表达式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date1 = null;
			String str = "";
			try {
				date1 = format.parse(datee);
				str = sdf.format(date1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			jpql += " and u.createTime <='" + str + "'";
		}
		 if(couponid!=null&&!couponid.equals("")){
			List<String>  pus= personalUserCouponRepository.findByOcId(couponid);
			if(pus.size()>0){
			String str=getServiceType(pus);
			jpql+="and u.id in("+str+")";
			}else{
				String sss="";
				jpql+="and u.id ='" + sss + "')" ;
			}
		 }
		Query query = manager.createQuery(jpql);
		List<Personelinfo> result = query.getResultList();
		Map<String, Object> map = new HashMap<>();
		map.put("total", result.size());
		query.setFirstResult(page * size);
		query.setMaxResults(size);
		List<Personelinfo> result1 = query.getResultList();
		map.put("userInfos", result1);
		return map;

	}
	
	public  List<Personelinfo> selectByAllAccountforUser(String starttime,String endtime) {
		String jpql = "select u from Personelinfo u where 1=1";
		if (starttime != null && !starttime.equals("")) {
			jpql += " and u.createTime >='" + starttime + "'";
		}
		if (endtime != null && !endtime.equals("")) {
			jpql += " and u.createTime <='" + endtime + "'";
		}
		Query query = manager.createQuery(jpql);
		List<Personelinfo> result1 = query.getResultList();
		return result1;

	}
	
	


	public static String getServiceType(List<String> ids){
		String str="";
		if(ids!=null){
			for(int k=0;k<ids.size();k++){
				if(k==0){
					str=str+"'"+ids.get(k)+"'";
				}else{
					str=str+",'"+ids.get(k)+"'";
				}
			}
		}
		return str;
	}
	
	public List<OperatorMailConfig> querymailConfig() {

		List<OperatorMailConfig> list = operatorMailConfigRepository.findAll();
		

		return list;
	}

	@Transactional
	public ReturnResult editmailConfig(String id, String account, String password, String recevieAdress,
			String issiueAdress, Integer status) {
		ReturnResult returnResult = new ReturnResult();
		OperatorMailConfig operatorMailConfig = operatorMailConfigRepository.findOne(id);
		if (operatorMailConfig != null) {
			operatorMailConfig.setAccount(account);
			operatorMailConfig.setPassword(password);
			operatorMailConfig.setReceiveserverAddress(recevieAdress);
			operatorMailConfig.setIssueserverAddress(issiueAdress);
			operatorMailConfig.setEffect(status);
			operatorMailConfigRepository.save(operatorMailConfig);
			returnResult.setKey("success");
			returnResult.setValue("修改成功");
		} else {
			OperatorMailConfig operatorMailConfig1=new OperatorMailConfig();
			operatorMailConfig1.setAccount(account);
			operatorMailConfig1.setPassword(password);
			operatorMailConfig1.setEffect(status);
			operatorMailConfigRepository.save(operatorMailConfig1);
			returnResult.setKey("success");
			returnResult.setValue("保存成功");
		
		}
		return returnResult;
	}

	@Transactional
	public ReturnResult addmail(String account, String password, String recevieAdress, String issiueAdress,
			String status) {
		ReturnResult returnResult = new ReturnResult();
		OperatorMailConfig operatorMailConfig = new OperatorMailConfig();
		operatorMailConfig.setAccount(account);
		operatorMailConfig.setPassword(password);
		operatorMailConfig.setReceiveserverAddress(recevieAdress);
		operatorMailConfig.setIssueserverAddress(issiueAdress);
		if (status.equals("是")) {
			operatorMailConfig.setEffect(0);
		} else {
			operatorMailConfig.setEffect(1);
		}
		operatorMailConfigRepository.save(operatorMailConfig);
		returnResult.setKey("success");
		returnResult.setValue("保存成功");

		return returnResult;
	}

	@Transactional
	public ReturnResult personalAccountSetting(String name, String email, String userid) {
		ReturnResult returnResult = new ReturnResult();
		OperatorUser operatorUser = operatorUserRepository.findOne(userid);
		if (operatorUser != null) {
			operatorUser.setName(name);
			operatorUser.setUserEmail(email);
			operatorUserRepository.save(operatorUser);
			returnResult.setKey("success");
			returnResult.setValue("修改成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("修改失败");
		}
		return returnResult;
	}

	public OperatorUser personalAccountSettinginfo(String userid) {
		OperatorUser operatorUser = operatorUserRepository.findOne(userid);
		if (operatorUser != null) {
			operatorUser.setRoles(null);
			if (operatorUser.getDepartmentId() != null) {
				OperatorDepartment operatorDepartment = operatorDepartmentRepository
						.findOne(operatorUser.getDepartmentId());
				operatorUser.setDepartmentId(operatorDepartment.getDepname());
			}
			if (operatorUser.getRoleId() != null) {
				OperatorRole operatorRole = operatorRoleRepository.findOne(operatorUser.getRoleId());
				operatorUser.setRoleId(operatorRole.getRolename());
			}
			return operatorUser;
		}
		return null;
	}

	@Transactional
	public ReturnResult personalAccountSettingPwd(String password, String userid) {
		ReturnResult returnResult = new ReturnResult();
		OperatorUser operatorUser = operatorUserRepository.findOne(userid);
		if (operatorUser != null) {
			operatorUser.setPassword(password);
			operatorUserRepository.save(operatorUser);
			returnResult.setKey("success");
			returnResult.setValue("修改成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("修改失败");
		}
		return returnResult;
	}

	public ReturnResult vlidateCodeIsexist(String username, String code) {
		ReturnResult returnResult = new ReturnResult();
		List<OperatorUser> operUserList = operatorUserRepository.findUserByUsername(username);
		if (operUserList.size() > 0) {
			List<OperatorCode> list = operatorCodeRepository.findCodeByTelephone(operUserList.get(0).getUserPhone());
			if (list == null || list.size() == 0) {
				returnResult.setKey("error");
				returnResult.setValue("用户名不正确");
			} else {
				OperatorCode personalCode = list.get(0);
				if (personalCode.getCodetext() != null && code != null && personalCode.getCodetext().equals(code)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
					String date1 = df.format(new Date());// new Date()为获取当前系统时间
					String date2 = df.format(personalCode.getDate());
					String str = getDistanceTime(date1, date2);
					if (Integer.parseInt(str) >= 5) {
						returnResult.setKey("error");
						returnResult.setValue("验证码过期请重新获取");
					} else {
						returnResult.setKey("success");
						returnResult.setValue("验证成功");
					}
				} else {
					returnResult.setKey("error");
					returnResult.setValue("验证码错误");
				}
			}
		}

		return returnResult;
	}

	/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * 
	 * @param str1
	 *            时间参数 1 格式：1990-01-01 12:00:00
	 * @param str2
	 *            时间参数 2 格式：2009-01-01 12:00:00
	 * @return String 返回值为：xx天xx小时xx分xx秒
	 */
	public static String getDistanceTime(String str1, String str2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return min + "";
	}

	@Transactional
	public ReturnResult querymailpwd(String userid) {
		ReturnResult returnResult = new ReturnResult();
		OperatorQueryMailRecord OperatorQueryMailRecord = new OperatorQueryMailRecord();
		OperatorQueryMailRecord.setUserid(userid);
		OperatorUser operatorUser = operatorUserRepository.findOne(userid);
		OperatorQueryMailRecord.setQueryuname(operatorUser.getUsername());
		OperatorQueryMailRecord.setQuerytime(new Date());
		operatorQueryMailRecordRepository.save(OperatorQueryMailRecord);
		returnResult.setKey("success");
		return returnResult;

	}

	@Transactional
	public ReturnResult freezeuser(String id) {
		ReturnResult returnResult = new ReturnResult();
		PersonalUser user = personalUserRepository.findOne(id);
		if (user != null) {
			user.setIsFreeze("1");
			personalUserRepository.save(user);
			returnResult.setKey("success");
			returnResult.setValue("冻结成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("冻结失败");

		}
		return returnResult;
	}

	@Transactional
	public ReturnResult jihuofreezeuser(String id) {
		ReturnResult returnResult = new ReturnResult();
		PersonalUser user = personalUserRepository.findOne(id);
		if (user != null) {
			user.setIsFreeze("2");
			personalUserRepository.save(user);
			returnResult.setKey("success");
			returnResult.setValue("解冻成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("解冻失败");
		}
		return returnResult;
	}
	
	
	
}
